<template>
  <div :class="ns.b()">
    <span :class="ns.e('label')" v-if="showTitle">{{ title }}</span>
    <div v-click-outside="handleClickOut">
      <search-input v-model="searchTxt" :width="width" :clearable="clearable" :prefixIcon="{ icon: 'vi-sousuo', color: '#666666', cursor: true }" :suffixIcon="{}" :placeholder="placeholder" @focus="hanleInputFocus" @enter="handleEnter" @clear="handleClear">
        <div v-show="isFocused" :class="ns.e('content')">
          <div :class="ns.e('title')">
            最近搜索
            <i :class="ns.e('icon-delete')" title="清空" @click="deleteHistory" />
          </div>
          <div :class="ns.e('historyList')">
            <span :class="ns.e('item')" v-for="item in historyTagList" :key="item" @click="historyTagClickFn(item)">
              {{ item }}
            </span>
          </div>
        </div>
      </search-input>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { useNamespace } from 'vc/src/use';
import SearchInput from '@/components/search/index.vue';

const ns = /* hoist-static*/ useNamespace('search-history');
defineOptions({ name: ns.b() });

interface Prop {
  modelValue?: string | number;
  title?: string;
  placeholder?: string;
  clearable?: boolean;
  width?: Numberish;
  showTitle?: boolean;
}

function handleClickOut() {
  handleEnter(searchTxt.value);
}
const { modelValue = '', title = '企业名称', placeholder, clearable = true, width = 200, showTitle = true } = defineProps<Prop>();

const emit = defineEmits(['update:modelValue', 'input', 'focus', 'blur', 'enter', 'clear']);

const searchTxt = computed({
  get() {
    return modelValue;
  },
  set(value) {
    emit('update:modelValue', value);
  }
});

const isFocused = ref(false);

const hanleInputFocus = () => {
  isFocused.value = true;
};

const handleEnter = (val) => {
  isFocused.value = false;
  setHistory(val);
  emit('enter', val);
};

const handleClear = () => {
  searchTxt.value = '';
  emit('clear');
};

// 历史记录
const historyTagList = ref<string[]>([]);

// 根据路径获取模块名
const pathArr = location.pathname.split('/');
const pathKey = pathArr[pathArr.length - 1];

let searchHistoryTag = {};

// 储存历史搜索
const setHistory = (val) => {
  if (!val) {
    return;
  }
  historyTagList.value = historyTagList.value.filter((item) => item !== val);
  if (historyTagList.value.length === 20) {
    historyTagList.value.pop();
  }
  historyTagList.value.unshift(val);
  searchHistoryTag[pathKey] = historyTagList.value;
  localStorage.setItem('searchHistoryTag', JSON.stringify(searchHistoryTag));
};

// 获取历史搜索
const getHistory = () => {
  const allHistoryTag = localStorage.getItem('searchHistoryTag');
  const searchHistoryTag = allHistoryTag ? JSON.parse(allHistoryTag) : {};
  historyTagList.value = searchHistoryTag[pathKey] || [];
};

// 清空历史搜索
const deleteHistory = () => {
  historyTagList.value = [];
  searchHistoryTag[pathKey] = [];
  localStorage.setItem('searchHistoryTag', JSON.stringify(searchHistoryTag));
};

const historyTagClickFn = useDebounceFn((val) => {
  emit('update:modelValue', val);
  handleEnter(val);
}, 100);

getHistory();
</script>

<style lang="scss" scoped>
@include b('search-history') {
  display: inline-flex;
  align-items: center;
  gap: 12px;
  @include e(label) {
    font-size: 13px;
    color: #606266;
  }
  :deep(.vc-input) {
    line-height: unset;
    .vc-input__wrapper {
      padding: 0 11px;
      border-radius: 4px;

      .vc-input__inner {
        height: 28px;
        line-height: unset;
        font-size: 13px;
      }
    }
  }
  :deep(.vc-input__wrapper.is-focus){
      box-shadow: #02C680 0 0 0 1px inset ;
    } 
  @include e('content') {
    margin: 14px 0;
    padding: 0 14px;
    box-sizing: border-box;
    height: 200px;
    overflow-y: auto;
    @include scroll-bar();

    @include e(title) {
      display: flex;
      align-items: center;
      font-weight: 500;
      font-size: 14px;
      line-height: 22px;
      color: #000;
      @include e(icon-delete) {
        display: inline-block;
        width: 12px;
        height: 13px;
        cursor: pointer;
        margin-left: 12px;
        background-image: url('@/assets/delete.png');
        background-size: 100% 100%;
        background-repeat: no-repeat;
      }
    }
    @include e(historyList) {
      margin-top: 8px;
      display: flex;
      flex-wrap: wrap;
      gap: 12px;
      @include e(item) {
        display: inline-flex;
        align-items: center;
        padding: 0 10px;
        height: 28px;
        font-size: 14px;
        color: #282828;
        background: #f6f6f6;
        cursor: pointer;
      }
    }
  }
}
</style>
